/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 11:18:39   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zx.cloud.domain.ClientAuth;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.VerifyMsg;
import com.zx.cloud.persistence.ClientAuthMapper;
import com.zx.cloud.persistence.ClientInfoMapper;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;
import com.zx.cloud.util.MessageVerificationUtils;

/**
 * 
 */
@Service
public class VerifyMsgService extends CrudServiceImpl<VerifyMsg>{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(VerifyMsgService.class);
    
    @Autowired
    private ClientAuthMapper clientAuthMapper;
    
    @Autowired
    private ClientInfoMapper clientInfoMapper;
    
	@Autowired
	private DictMapper dictMapper;
    
  	@Autowired
    public VerifyMsgService(CrudMapper<VerifyMsg> mapper) {
        super(mapper);
    }
  	
  	public String handleCheckLiveness(String filePath, String fileUrl, String fileId){
  		
  		String resultStatus = null;
  		
  		String resultResponse = MessageVerificationUtils.checkLiveness(filePath, fileUrl, fileId);
  		
  		if(StringUtils.isNotEmpty(resultResponse)){
  			
  			JsonObject jsonObject = new JsonParser().parse(resultResponse).getAsJsonObject();
  			
  			String status = jsonObject.get("status").getAsString();
			resultStatus = status;
  		}
  		
  		return resultStatus;
  	}

  	public String handleVerification(String filePath, Long userId){
  		
  		String resultStatus = null;
  		
  		Map<String, Object> params = new HashMap<String, Object>();
  		
  		/*
		 * 获取数据库OCR接口相关配置
		 */
		Dict dict = new Dict();
		dict.setParentCode("LF0001");
		List<Dict> dicts = dictMapper.getDitByParentCode(dict);
		if(null != dicts && dicts.size() > 0){
			for(int i = 0; i < dicts.size(); i++){
				params.put(dicts.get(i).getName(), dicts.get(i).getValue());
			}
		}
		
		String resultResponse = MessageVerificationUtils.parseIdcardOcrResult(params, filePath);
		
		if(StringUtils.isNotEmpty(resultResponse)){
			
			JsonObject jsonObject = new JsonParser().parse(resultResponse).getAsJsonObject();
			
			String status = jsonObject.get("status").getAsString();
			resultStatus = status;
			
			ClientAuth clientAuth = clientAuthMapper.findByClientID(userId); //认证信息
			
			ClientInfo clientInfo = clientInfoMapper.findClientById(userId); //详细信息
			
			LOGGER.info("*******************************获取接口返回状态码："+ status +"************************************");
			
			if("OK".equals(status)){
				
				VerifyMsg verifyMsg = new VerifyMsg();
				
				String info = jsonObject.get("info").getAsString();
				JsonObject infoJson = new JsonParser().parse(info).getAsJsonObject();
				
				String name = infoJson.get("name").getAsString();
				JsonObject nameJson = new JsonParser().parse(name).getAsJsonObject();
				verifyMsg.setName(nameJson.get("text").getAsString());
				clientInfo.setRealName(nameJson.get("text").getAsString());
				
				String sex = infoJson.get("sex").getAsString();
				JsonObject sexJson = new JsonParser().parse(sex).getAsJsonObject();
				verifyMsg.setSex(sexJson.get("text").getAsString());
				clientInfo.setSex(sexJson.get("text").getAsString());
				
				String nation = infoJson.get("nation").getAsString();
				JsonObject nationJson = new JsonParser().parse(nation).getAsJsonObject();
				verifyMsg.setNation(nationJson.get("text").getAsString());
				clientInfo.setNational(nationJson.get("text").getAsString());
				
				String year = infoJson.get("year").getAsString();
				JsonObject yearJson = new JsonParser().parse(year).getAsJsonObject();
				verifyMsg.setYear(yearJson.get("text").getAsString());
				
				String month = infoJson.get("month").getAsString();
				JsonObject monthJson = new JsonParser().parse(month).getAsJsonObject();
				verifyMsg.setMonth(monthJson.get("text").getAsString());
				
				String day = infoJson.get("day").getAsString();
				JsonObject dayJson = new JsonParser().parse(day).getAsJsonObject();
				verifyMsg.setDay(dayJson.get("text").getAsString());
				
				String address = infoJson.get("address").getAsString();
				JsonObject addressJson = new JsonParser().parse(address).getAsJsonObject();
				verifyMsg.setAddress(addressJson.get("text").getAsString());
				clientInfo.setIdAddr(addressJson.get("text").getAsString());
				
				String idNum = infoJson.get("idNum").getAsString();
				JsonObject idNumJson = new JsonParser().parse(idNum).getAsJsonObject();
				verifyMsg.setIdnum(idNumJson.get("text").getAsString());
				clientInfo.setId(new Long(idNumJson.get("text").getAsString()));
				
				String authority = infoJson.get("authority").getAsString();
				JsonObject authorityJson = new JsonParser().parse(authority).getAsJsonObject();
				verifyMsg.setAuthority(authorityJson.get("text").getAsString());
				
				String validity = infoJson.get("validity").getAsString();
				JsonObject validityJson = new JsonParser().parse(validity).getAsJsonObject();
				verifyMsg.setValidity(validityJson.get("text").getAsString());
				
				verifyMsg.setCreateDate(OffsetDateTime.now());
				verifyMsg.setRemark(userId+"");
				
				LOGGER.info("*******************************保存ocr接口返回数据入库************************************");
				super.insert(verifyMsg);
				
				if(null != clientAuth){
					clientAuth.setIdState(1); //认证成功
				}
				
				clientInfo.setUpdateTime(OffsetDateTime.now());
				clientInfoMapper.update(clientInfo);
			}else{
				if(null != clientAuth){
					clientAuth.setIdState(2); //认证失败
				}
			}
			
			clientAuth.setIdTime(OffsetDateTime.now());
			clientAuthMapper.update(clientAuth);
		}
  		
  		return resultStatus;
  	}

}
